class BaseTree {
    constructor(instance, getTreeUrl, dragUrl, stateKey) {
        this.stateKey = stateKey;    // 树状态保存key "huzo_selected_node"
        this.getTreeUrl = getTreeUrl;
        this.dragUrl = dragUrl;
        this.instance = instance;
        this.first = 0;
        this.draggable = 1;          // 拖动开关
        this.draggedItemList = [];   // 要拖动的对象
        this.beginMoving = false;
        this.defaultNode = "j1_1";   // 初始要显示的节点（默认是根节点）
        this.isChoice = 0;           // 指示是否为弹出选择窗口，这对初始化有帮助
    }
    InitTreeObject() {
        // 初始化树形控件
        $('#treeContent').jstree({
            "core": {
                "animation": 200,
                "multiple": false,
                "check_callback": true,
                "themes": {
                    "responsive": true,
                    "dots": false,
                    "icons": true
                },
                "data": {
                    'dataType': 'JSON',
                    'contentType': 'application/json; charset=utf-8',
                    'type': 'GET',
                    'url': parent.basePath + this.getTreeUrl,
                    'data': (node) => {
                        let _nodeId = node.id === '#' ? -1 : (node.id === 'j1_1' ? 0 : node.id);
                        return {'parentKey': _nodeId, 'isPopupWnd': 0, 'isAdministrator': 1};
                    },
                    'complete': () => {
                        if (this.instance.flag === undefined || parseInt(this.instance.flag) === 0) {
                            let ref = $.jstree.reference('treeContent');
                            ref.clear_state();
                        }
                    }
                }
            },
            "types": {
                "#": {"max_depth": -1, "max_children": -1, "valid_children": ["root"]},
                "root": {"max_depth": -1, "max_children": -1, "icon": parent.basePath + "/images/tree/root.png", "valid_children": -1},
                "default": {"max_depth": -1, "max_children": -1, "valid_children": -1},
                "leaf": {"max_depth": -1, "max_children": -1, "icon": parent.basePath + "/images/tree/folder_close.png", "valid_children": -1},
                "trash": {"max_depth": -1, "max_children": -1, "icon": parent.basePath + "/images/tree/trash.png", "valid_children": -1}
            },
            "state": {"key": this.stateKey},
            "plugins": ["state", "types", "wholerow"]
        });
        $('#treeContent').on('select_node.jstree', (event, data) => {
            let _nodeIdOfSelected = data.node.id;

            // 设置选择节点信息
            let _nodeId = _nodeIdOfSelected === "j1_1" ? "0" : _nodeIdOfSelected;
            $("#NodeId").val(_nodeId);
            let _nodeOfSelected = $("#" + _nodeIdOfSelected);
            $("#NodeText").val(_nodeOfSelected.attr("fullname"));
            $("#NodeLevel").val(_nodeOfSelected.attr("aria-level"));       // 节点级别

            // 得到该目录全部数据
            this.instance.filterCatalogueFlag = 1;
            if (this.first === 0) {
                let _pageindex = 1;
                if ($.cookie !== undefined) {
                    _pageindex = $.cookie(this.instance.cokiePageIndex) === undefined ? 1 : $.cookie(this.instance.cokiePageIndex);
                }
                this.instance.FetchForPage(_pageindex);
                this.first = 1;
            } else {
                this.instance.FetchForPage(1);
                //this.instance.FetchAll();
                if (this.first > 1)
                    this.isChoice = 0;
            }

            // 设置全选框状态
            $("#CheckAll").prop("checked", false);
        });
        // 节点展开后，重新设置图标
        $('#treeContent').on('open_node.jstree', (event, data) => {
            let ref = $.jstree.reference('treeContent');
            let _nodeIdOfSelected = data.node.id;
            let _nodeOfSelected = $("#" + _nodeIdOfSelected);
            if (_nodeIdOfSelected !== "j1_1") {
                if (ref.get_type(_nodeOfSelected) !== "trash") {
                    ref.set_icon(_nodeOfSelected, parent.basePath + "/images/tree/folder_open.png");
                } else {
                    ref.set_icon(_nodeOfSelected, parent.basePath + "/images/tree/trash_o.png");
                }
            }
        });
        // 节点打开后
        $('#treeContent').on('after_open.jstree', (event, data) => {
            let ref = $.jstree.reference('treeContent');
            if (parseInt(this.isChoice) === 1 && this.first === 1) {
                if (this.defaultNode === '花仔') {
                    let _obj = $('li[fullname*="' + "车间" + '"]');
                    ref.open_node(_obj);
                    this.first = 2;
                } else {
                    if ($('li[fullname*="' + this.defaultNode + '"]').length > 0) {
                        let _obj = $('li[fullname*="' + this.defaultNode + '"]');
                        ref.select_node(_obj);
                        this.first = 2;
                    }
                }
            }
            if (parseInt(this.isChoice) === 1 && this.first === 2) {
                if (this.defaultNode === '花仔') {
                    let _obj = $('li[fullname*="' + this.defaultNode + '"]');
                    ref.select_node(_obj);
                }
            }
        });
        // 节点收回后，重新设置图标
        $('#treeContent').on('close_node.jstree', (event, data) => {
            let ref = $.jstree.reference('treeContent');
            let _nodeIdOfSelected = data.node.id;
            let _nodeOfSelected = $("#" + _nodeIdOfSelected);
            if (_nodeIdOfSelected !== "j1_1") {
                if (ref.get_type(_nodeOfSelected) !== "trash") {
                    ref.set_icon(_nodeOfSelected, parent.basePath + "/images/tree/folder_close.png");
                } else {
                    ref.set_icon(_nodeOfSelected, parent.basePath + "/images/tree/trash.png");
                }
            }
        });
        // 所有节点完成装载，只运行一次
        $('#treeContent').on('ready.jstree', () => {
            let ref = $.jstree.reference('treeContent');

            if (parseInt(this.isChoice) === 1) {
                this.first = 1;
                let _obj = $("#j1_1");
                ref.open_node(_obj);     // 打开当前第一层节点
                if (this.defaultNode === "j1_1") {
                    ref.select_node(_obj);
                } else {
                    ref.deselect_node(_obj);
                }
            } else {
                if (this.instance.flag === undefined || parseInt(this.instance.flag) === 0) {
                    this.first = 1;
                    ref.clear_state();
                    let _obj = $("#j1_1");
                    ref.open_node(_obj);     // 打开当前第一层节点
                    ref.select_node(_obj);
                } else {
                    ref.restore_state();
                }
            }
        });
        // 节点恢复完成
        $('#treeContent').on('state_ready.jstree', (event, data) => {
            let ref = $.jstree.reference('treeContent');
            // 如果没有恢复，即有没有默认的选择节点，那么就设置根节点
            if (ref.get_selected(false).length === 0) {
                let _obj = $("#j1_1");
                ref.open_node(_obj);
                ref.select_node(_obj);
                //$("#loading").hide();
            }
        });
        if (this.isChoice === 0) {
            // 鼠标移动事件(为选择窗口时，则没有下面事件)
            $('#treeContent').on('hover_node.jstree', (event, data) => {
                let _hoverNodeId = data.node.id;
                let _hoverNode = $("#" + _hoverNodeId);

                if (parseInt(this.draggable) === 1) {
                    _hoverNode.unbind('mouseup').mouseup((event) => {
                        let _this = this.instance;
                        _hoverNode.unbind('mouseup');
                        for (let i = 0; i < _this.draggedItemList.length; i++) {
                            _this.draggedItemList[i]['catalogueId'] = _hoverNodeId === "j1_1" ? 0 : _hoverNodeId;
                            _this.draggedItemList[i]['updatedBy'] = $("#UserId").val();
                        }
                        let itemResult = {};
                        itemResult['updateList'] = _this.draggedItemList;
                        if (_this.draggedItemList.length) {
                            $.ajax({
                                type: "POST",
                                url: parent.basePath + this.dragUrl,
                                timeout: 30 * 1000,
                                data: JSON.stringify(itemResult),
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                beforeSend: () => {
                                }
                            }).done(() => {
                                // 设置全选框状态
                                $("#CheckAll").prop("checked", false);
                                ShowSuccessMessagePanel('目录改变成功。');
                                // 刷新列表
                                let currPage = _this.$pagination.attr("_msh_page");
                                _this.FetchForPage(currPage);
                            }).fail((data) => {
                                ajaxError(data, 1);
                            }).always(( ) => {
                            });
                        }
                        // 清空选择的行和数据，防止出现父节点也被拖进去的现象
                        _this.selectedItemList = {};
                        _this.draggedItemList = [];
                        _hoverNode.unbind('mouseup');
                    });
                    event.stopPropagation();
                }
            });
        }
    }
    CreateDragLayer(e) {
        $('<div id="moveLayerId" class="lines__dragging"><i class="fa-all fa-2 fa-file-text-o"></i></div>').appendTo($('body'));
        $("#moveLayerId").css({left: e.clientX - 5, top: e.clientY - 35});
    }
    FollowMe(e) {
        if (window.getSelection) {
            window.getSelection().removeAllRanges();
        } else {
            document.selection.empty();
        }
        let left = Math.max(e.clientX - 5, 20);
        let top = Math.max(e.clientY - 35, 20);
        $("#moveLayerId").css({left: left, top: top});
    }
    MouseDownToMove(obj) {
        obj.style.zIndex = 1;
        obj.mouseDownY = event.clientY;
        obj.mouseDownX = event.clientX;
        this.beginMoving = true;
    }
    // 鼠标拖动操作事件
    MouseMoveToMove(obj) {
        if (!this.beginMoving)
            return false;
        obj.style.top = (event.clientY - obj.mouseDownY);
        obj.style.left = (event.clientX - obj.mouseDownX);

        return false;
    }
    // 鼠标松开操作事件
    MouseUpToMove(obj) {
        if (!this.beginMoving)
            return false;
        obj.releaseCapture();
        obj.style.top = 0;
        obj.style.left = 0;
        obj.style.zIndex = 0;
        beginMoving = false;
        let tempTop = event.clientY - obj.mouseDownY;
        let tempRowIndex = (tempTop - tempTop % 25) / 25;
        if (tempRowIndex + obj.rowIndex < 0)
            tempRowIndex = -1;
        else
            tempRowIndex = tempRowIndex + obj.rowIndex;
        if (tempRowIndex >= obj.parentElement.rows.length - 1)
            tempRowIndex = obj.parentElement.rows.length - 1;
        obj.parentElement.moveRow(obj.rowIndex, tempRowIndex);
    }
}